'''
Created on Aug 28, 2013

@author: loski
'''

import os
import shutil

class SongManager(object):
    '''
    Class that copies the folder tree to the target
    '''
    def walk_dir(self, current_dir, tgt):
        base_path = os.path.basename(current_dir)
        real_tgt = os.path.join(tgt, base_path)
        if not os.path.exists(real_tgt):
            os.makedirs(real_tgt)
        
        aux_listdir = os.listdir(current_dir)
        aux_listdir.sort()
        for x in aux_listdir:
            if not x.startswith('.'):
                subitem = os.path.join(current_dir, x)
                if os.path.isdir(subitem):
                    self.walk_dir(subitem, real_tgt)
                else:
                    if subitem[-4:].lower() in ['.mp3', '.wma']:
                        self.copy_song(current_dir, x, real_tgt)
    
    def walk_dir_id3(self, current_dir, tgt):
        try:
            from mutagen.easyid3 import EasyID3
            base_path = os.path.basename(current_dir)
            real_tgt = os.path.join(tgt, base_path)
            if not os.path.exists(real_tgt):
                os.makedirs(real_tgt)
            
            list_of_songs = []
            for x in os.listdir(current_dir):
                if not x.startswith('.'):
                    subitem = os.path.join(current_dir, x)
                    if os.path.isdir(subitem):
                        self.walk_dir_id3(subitem, real_tgt)
                    else:
                        if subitem[-4:].lower() in ['.mp3', '.wma']:
                            list_of_songs.append({'path': x, 'tracknumber': EasyID3(subitem)['tracknumber']})
            
            from operator import itemgetter
            sorted_list_of_songs = sorted(list_of_songs, key=itemgetter('tracknumber'))
            for x in sorted_list_of_songs:
                self.copy_song(current_dir, x['path'], real_tgt)
        except:
            print "No mutagen lib available, flag --id3 ignored."
            self.walk_dir(current_dir, tgt)
    
    def copy_song(self, src_path, song_name, tgt_path):
        tgt_song_path = os.path.join(tgt_path, song_name)
        src_song_path = os.path.join(src_path, song_name)
        shutil.copy(src_song_path, tgt_song_path)